package com.gigrt.midend.marketing.impl.infrastructure.eventbus;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import static java.util.concurrent.Executors.newFixedThreadPool;

@Component
public class DomainEventBus implements IDomainEventBus {

    @Value("spring.application.name")
    private String identifier;

    private EventBus eventBus;

    private AsyncEventBus asyncEventBus;

    @PostConstruct
    public void init() {
        this.eventBus = new EventBus(identifier);
        this.asyncEventBus = new AsyncEventBus(identifier, newFixedThreadPool(50));
    }

    @Override
    public void register(Object subscriber) {
        this.eventBus.register(subscriber);
    }

    @Override
    public void unregister(Object subscriber) {
        this.eventBus.unregister(subscriber);
    }

    @Override
    public void publish(IDomainEvent event) {
        if(event.isSync()){
            this.eventBus.post(event);
        }else {
            this.asyncEventBus.post(event);
        }

    }
}